/* eslint-disable */
<template>
	<!-- 批量分配角色权限 -->
	<div>
		<el-dialog class="handleDialog" :title="title" :visible.sync="show"   width="60%"  :close-on-click-modal="false"  @close="closeDiolag">
			<el-row>
			  <el-form :rules="rules"  :inline="false"  :model="roleForm" ref="roleForm" label-width="110px">
	                <el-row>
	                	<el-col :span="18" >
							<span style="font-weight:bold;">{{$t('components.handleRoleBatch.step1')}}：</span>{{$t('components.handleRoleBatch.selectByAccountTip')}}
					 	</el-col>
	                	<!--操作按钮-->
						<el-col :span="6" class="alignC">
					  		<el-button size="small"  type="primary"  @click="addAccountVisible=true;accountText='';accountTextList=[]" >{{$t('components.handleRoleBatch.batchAdd')}}</el-button>
					  		<el-button size="small"  type="danger"  @click="removeSelect" >{{$t('components.handleRoleBatch.batchDelete')}}</el-button>
						</el-col>
	                </el-row>
	                <el-row>
	                    <el-col :span="24">
							<el-table v-loading="loadind1"   ref="roletableList" :data="roletableList" border max-height="500"  style="width: 100%" @selection-change="selectAddListChange" >
					  		 	<el-table-column  type="selection" width="55"></el-table-column>
					  		 	<el-table-column prop="byAccountName" :label="$t('common.byUserName')+':'"   show-overflow-tooltip></el-table-column>
							    <el-table-column prop="empName" :label="$t('components.handleRoleBatch.empName')+':'"  show-overflow-tooltip> </el-table-column>
							    <el-table-column prop="positionName" :label="$t('common.positionName')+':'"  show-overflow-tooltip> </el-table-column>
							    <el-table-column prop="orgName" :label="$t('common.orgName')+':'"  show-overflow-tooltip> </el-table-column>
							    <el-table-column prop="netCode" :label="$t('common.netCode')+':'"  show-overflow-tooltip> </el-table-column>
							</el-table>
							<p>{{$t('components.handleRoleBatch.totalCounts')}}:
			                    <span class="addtionTableSpan">{{roletableList.length}}</span>
			                    <span style="color:red;font-size:12px;" v-if="roletableList.length>200">({{$t('components.handleRoleBatch.overflowTip')}})</span>
		                    </p>
						</el-col>
	                </el-row>
	                <p><span style="font-weight:bold;">{{$t('components.handleRoleBatch.step2')}}：</span>{{$t('components.handleRoleBatch.selectRole')}}  </p>
	                <el-row>
						<el-col :span="9">
							<el-form-item  :label="$t('common.subsysName')+':'" prop="subsysName">
								<el-select  v-model="roleForm.subsysName" :placeholder="$t('common.selectPlaceholder')" >
									<el-option  @click.native="handleSelectSubsys(item)" v-for="(item,index) in subsysTemOptions" :key="index" :label="item.label" :value="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="9">
							<el-form-item  :label="$t('common.roleName')+':'" prop="roleName">
								<el-select v-model="roleForm.roleName" filterable :placeholder="$t('common.selectPlaceholder')"   :filter-method="getroleList">
								    <el-option
								      v-for="(item,index) in roleNameOptions" :key="index" :label="item.roleName"  :value="item.roleId">
								    </el-option>
								</el-select>
							</el-form-item>
						</el-col>
	                </el-row>
	                <p ><span style="font-weight:bold;">{{$t('components.handleRoleBatch.step3')}}：</span>{{$t('components.handleRoleBatch.maintainDate')}} </p>
	                <el-row >
	                    <el-col :span="24">
	                        <el-form-item :label="$t('common.startTm')+':'" class="is-required" :class="(showError && !roleForm.startTm)?'is-error':''">
	                        	<el-date-picker @change="checkDateValid('startTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd"    v-model="roleForm.startTm"  type="date"  :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleRoleBatch.completionStartTime')}}）</span>
						    	<div class="el-form-item__error" v-if="showError && !roleForm.startTm">
						        	{{$t('validateWornText.slectStartTm')}}
						        </div>
	                        </el-form-item>
	                    </el-col>
	                     <el-col :span="24">
	                        <el-form-item :label="$t('common.endTm')+':'"  class="is-required" :class="(showError && !roleForm.endTm)?'is-error':''">
	                        	<el-date-picker @change="checkDateValid('endTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd"    v-model="roleForm.endTm"  type="date"  :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleRoleBatch.completionEndTime')}}）</span>
						    	<div class="el-form-item__error" v-if="showError && !roleForm.endTm">
						        	{{$t('validateWornText.slectEndTm')}}
						        </div>
	                        </el-form-item>
	                    </el-col>
	                </el-row>
	            </el-form>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button @click="$emit('exit') ">{{$t('common.giveUp')}}</el-button>
				<el-button type="primary" @click="save">{{$t('common.save')}}</el-button>
			</div>
		</el-dialog>
		<!--批量添加账号-->
		<el-dialog class="newlyForm" :title="$t('components.handleRoleBatch.batchAdd')" :visible.sync="addAccountVisible"  width="60%" :close-on-click-modal="false">
		    <el-row >
	            <p>{{$t('components.handleResourceBatch.inputByAccount')}}</p>
	            <el-input @blur="getFocusVisible=false " @change="getFocusChange" v-if="getFocusVisible" :maxlength="2000" type="textarea" :rows="8" v-model="accountText"></el-input>
	        	<div style="min-height:180px;overflow: auto;" class="el-textarea__inner" @click="getFocusVisible=true" v-if="!getFocusVisible">
	        		<span :keys="index" :key="index" v-for="(item,index) in accountTextList"><span :class="item.flag? 'normalText':'errorText'">{{item.label}}</span><span v-if="index!=accountTextList.length-1">,</span></span>
	        	</div>
		   		<div style="margin-top: 5px;">{{$t('components.handleResourceBatch.supportMatAccount') }}</div>
		    </el-row >
			<div slot="footer" class="dialog-footer">
				<el-button @click="addAccountVisible=false;">{{$t('common.giveUp')}}</el-button>
				<el-button type="primary" @click="saveAccount">{{$t('common.save')}}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
    Message, Notification, MessageBox, Loading
} from 'element-ui'
export default {
    name: 'handleRole',
    props: [
        'visible'
    ],
    data () {
        return {
            show: false,
            roleForm: {
                subsysName: '',
                roleName: '',
                endTm: '',
                startTm: ''
            },
            pickerOptions1: {
                disabledDate (time) {
		            return (time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000)
		        }
            },
            rules: {
		        roleName: [
		            { required: true, message: this.$t('validateWornText.selectRoleName'), trigger: 'change' }
		        ],
		        subsysName: [
		            { required: true, message: this.$t('validateWornText.selectSubsysName'), trigger: 'change' }
		        ]
            },
            roleNameOptions: [],
            subsysTemOptions: [],
            roletableList: [],
            title: '',
            loadind1: false,
            addSelectMultipleSelection: [],
            showError: false,
            addAccountVisible: false,
            accountText: '',
            accountTextList: [],
            getFocusVisible: true
        }
    },
    watch: {
        visible: 'visibleChange'
    },
    mounted () {
    },
    methods: {
        visibleChange (val) {
            this.show = val
            if (val) {
                this.getSubSystemList() // 获取子系统
                this.title = this.$t('components.handleRoleBatch.assignRole')
            }
        },
        checkDateValid (param) {
            this.showError = !((this.roleForm.startTm && this.roleForm.endTm))
            if (this.roleForm.startTm != '' && this.roleForm.endTm != '') {
                if (this.roleForm.startTm > this.roleForm.endTm) {
                    this.$message({
				        message: this.$t('common.conmareEndTimeTip'),
				        type: 'warning'
				    })
                    this.roleForm[param] = ''
                }
            }
        },
        /**
		 * @author：xmj
		 * @function:获取子系统列表
		 */
        async getSubSystemList (val) {
            this.subsysTemOptions = await this.$getSubSystemList(val)
        },
        handleSelectSubsys (item) { // 选择子系统时查角色
            this.roleForm.subsysCode = item.value
            this.roleForm.roleName = ''
            this.getroleList('')
        },
        async getroleList (val) { // 根据子系统编码查角色
            this.roleForm.roleName = ""
            this.roleNameOptions = await this.getroleListFun(val, this.roleForm.subsysCode)
        },
        /**
		 * @author：mxj
		 * @function:根据系统，子系统，百源账号，角色名称模糊下拉框远程搜索，默认带出前10条，剩下的远程搜索下拉
		*/
        getroleListFun (queryString, subsysCode) {
            return new Promise((resolve, reject) => {
                if (/^[\u4e00-\u9fa5]/g.test(queryString) || /^\S{3,}$/.test(queryString) || queryString == '') {
                    this.$httpExt().post('/dev-basp-user/userRole/queryRoleForBatch', {
                        pageNum: 1,
                        pageSize: 10,
                        roleName: queryString,
                        subSystemCode: subsysCode
                    }).then(function (response) {
                        const results = response.result.data
                        resolve(results)
                    }, function (response) {
                        Message({
                            message: response.msg,
                            type: 'warning'
                        })
                    })
                } else {
                    resolve([])
                }
            })
        },
        selectAddListChange (val) { // 百源账号列表勾选
            this.addSelectMultipleSelection = val
        },
        save () {
            var that = this
	    	this.$refs['roleForm'].validate((valid) => {
			    if (valid) {
			    	if (!that.roleForm.endTm || !that.roleForm.startTm) { // 未填写失效时间,预申请未填写开始时间
			    		that.showError = true
			    	} else if (that.addSelectMultipleSelection.length < 1) { // 未勾选角色
			    		MessageBox({
                            message: this.$t('common.emptyTip'),
                            confirmButtonText: this.$t('common.iknow')
                        })
			    	} else { // 页面值校验通过
			    		that.$emit('roleHandleSave', that.roleForm, that.addSelectMultipleSelection)
			    	}
			    } else {
			    	if (!that.roleForm.endTm) { // 未填写失效时间
			    		that.showError = true
			    	} else if (!that.roleForm.startTm) { // 预申请未填写开始时间
			    		that.showError = true
			    	}
			    	return false
                }
            })
        },
        getFocusChange (param) {
            // 校验所填写工号是否合法
            var that = this
            this.$httpExt().post('/dev-basp-user/account/selectInvalidUsername', {// 查询填写的账号中不合法的账号
                usernames: this.accountText
            }).then(function (response) {
                if (response.result.length == 0 && param == 'submit') { // 没有不合法工号
                    that.submitAccount()
                } else {
                    var arr = that.accountText.split(',')
                    for (var i = 0; i < arr.length; i++) {
                        var tempindex = response.result.indexOf(arr[i])
                        if (tempindex > -1) {
                            arr[i] = {
                                label: arr[i],
                                flag: false
                            }
                        } else {
                            arr[i] = {
                                label: arr[i],
                                flag: true
                            }
                        }
                    }
                    that.accountTextList = arr
                    that.getFocusVisible = false
                }
            }, function (response) {
                that.accountTextList = that.accountText.split(',')
                that.getFocusVisible = false
                Message({
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText'),
                    type: 'warning'
                })
            })
        },
        submitAccount () { // 提交后台
            var that = this
            that.$httpExt().post('/dev-basp-user/account/queryAccountInfoList', {
                usernames: this.accountText
            }).then(function (response) {
                var arr = response.result
				 arr = arr.filter(item => {
				 	var temp = true
				 	for (var i = 0; i < that.roletableList.length; i++) {
				 		if (item.byAccountId == that.roletableList[i].byAccountId) {
				 			temp = false
				 			break
				 		}
				 	}
                    return temp
                })
                that.roletableList = that.roletableList.concat(arr)
                that.addAccountVisible = false
            }, function (response) {
                Message({
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText'),
                    type: 'warning'
                })
            })
        },
        saveAccount () {
            if (!this.accountText) {
                this.$message({
			          message: this.$t('components.handleRoleBatch.inputAccount'),
			          type: 'warning'
			    })
            } else { // 校验
                this.getFocusChange('submit')
            }
        },
        removeSelect () { // 将已勾选的选项删除
            for (var i = 0; i < this.addSelectMultipleSelection.length; i++) {
                var index = this.roletableList.indexOf(this.addSelectMultipleSelection[i])
                if (index > -1) {
                    this.roletableList.splice(index, 1)
                }
            }
        },
        reset () { // 重置模态框数据
            this.$refs['roleForm'].resetFields()// 重置表单
            this.roletableList = []
            this.addSelectMultipleSelection = []
            this.roleNameOptions = []
            this.subsysTemOptions = []
            this.showError = false
	    },
        closeDiolag () {
            this.reset()
            this.$emit('close')
        }
    }
}
</script>
<style lang="less" scoped>
.handleDialog{
	min-width: 1100px;
   .alignC {
	    text-align: right;
	    margin-bottom: 10px;
	}
	.addtionTableSpan{
	    display:inline-block;
	    width:auto;
	    height:15px;
	    padding:0px 5px;
	    line-height:15px;
	    text-align:center;
	    border:1px solid #ccc;
	    border-radius:2px;
	}
}
 p{
    display: block;
    -webkit-margin-before: 1em;
    -webkit-margin-after: 1em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
}
</style>
